<?php
/**
 * Created by PhpStorm.
 * User: jungshen
 * Date: 2018/7/26
 * Time: 14:24
 */
namespace app\api\controller\other;

use app\api\controller\BasicApi;
use app\api\service\MemberService;
use service\FileService;
use service\LogService;
use service\WechatService;
use Db;
use think\Exception;

class System extends BasicApi
{
    /**
     * 用户登录
     * @return \think\response\Json
     */
    public function login()
    {
        try{
            $code = $this->request->get('code');
            $parent_id = $this->request->get('parent_id',0);
            $encryptedData = $this->request->get('encryptedData');
            $iv = $this->request->get('iv');
            $data=WechatService::WeMiniCrypt()->userInfo($code,$iv,$encryptedData);
            if (!$data) {
                $return_data['msg']='解密数据失败';
                return json($return_data,504);
            }
            $openid = isset($data['unionId']) ? $data['unionId'] : $data['openId'];
            $user=Db::name('store_member')->where('openid',$openid)->find();
            $setMobile=false;
            $udata['nickname']=$data['nickName'];
            $udata['sex']=$data['gender']==1?'男':'女';
            if(!empty($user['id'])){
                if($user['phone']!='' && !empty($user['phone'])){
                    $setMobile=true;
                }
                $udata['id']=$user['id'];
                Db::name('store_member')->update($udata);
            }else{
                $udata['parent_id']=$parent_id;
                $udata['openid']=$openid;
                $udata['headimg']=$data['avatarUrl'];
                $udata['create_at']=date('Y-m-d H:i:s');
                $udata['type']=0;
                $udata['level']=1;
                $udata['status']=1;
                $udata['id']=Db::name('store_member')->insertGetId($udata);
            }
            $uid=$udata['id'];
            $user_token_record=Db::name('store_member_token')->where('mid',$uid)->find();
            $expires_in=$ut_data['expires_in']=time()+7200;
            $ut_data['mid']=$uid;
            if($user_token_record){
                if($user_token_record['expires_in']<=time()){
                    $ut_data['logintoken']=createRandomStr(32);
                }else{
                    $ut_data['logintoken']=$user_token_record['logintoken'];
                }
                $re=Db::name('store_member_token')->update($ut_data);
            }else{
                $ut_data['logintoken']=createRandomStr(32);
                $re=Db::name('store_member_token')->insert($ut_data);
            }
            if(!$re){
                $return_data['msg']='登录失败';
                return json($return_data,500);
            }else{
                $return_data['msg']='登录成功';
                $_res['user_token']=$ut_data['logintoken'];
                $_res['user_id']=$ut_data['mid'];
                $_res['expires_in']=$expires_in;
                $_res['set_mobile']=$setMobile;
                $return_data['data']=$_res;
                return json($return_data);
            }
        }catch (\Exception $e){
            return json(array('msg'=>$e->getMessage()),500);
        }
    }

    /**
     * 获取我的分类列表
     * @return \think\response\Json
     */
    public function my_cate_list()
    {
        try{
            $pid=input('get.pid',33);
            $db=Db::name('my_cate')->order('sort');
            $db->where('status',1);
            if(is_numeric($pid)){
                $db->where('pid',$pid);
            }else{
                $db->whereIn('pid',$pid);
            }
            $list=$db->field('id,icon,content,title')->select();
            $data['msg']='success';
            $data['data']=$list;
            return json($data);
        }catch (\Exception $e){
            return json(array('msg'=>$e->getMessage()),500);
        }
    }

    /**
     * 获取系统分类列表
     * @return \think\response\Json
     */
    public function system_cate_list()
    {
        try{
            $pid=input('get.pid');
            $is_push=input('get.is_push',0);
            if(empty($pid)){
                throw new \Exception('上级ID不能为空',500);
            }
            $whr[]=['status','=',1];
            if(is_numeric($pid)){
                $whr[]=['pid','=',$pid];
            }else{
                $whr[]=['pid','in',$pid];
            }
            if($is_push){
                $whr[]=['allow_publish','=',1];
            }
            $list=app('systemCateService')::get_cate_list($whr,'id,icon,title');
            $data['msg']='success';
            $data['data']=$list;
            return json($data);
        }catch (\Exception $e){
            return json(array('msg'=>$e->getMessage()),500);
        }
    }

    /**
     * 获取城市数据
     * @return \think\response\Json
     */
    public function city()
    {
        try{
            $level=input('level',3);
            $list=Db::name('system_city')->where('status',1)->order('sort,id')->field('name,id,pid')
                ->where('pid',0)->cache(true,60*60*60*24*365*10)->select();
            if($level==3){
                foreach ($list as $p_k => $province) {
                    $citylist=Db::name('system_city')->where('status',1)->order('sort,id')->field('name,id,pid')
                        ->where('pid',$province['id'])->cache(true,60*60*60*24*365*10)->select();
                    if(!empty($citylist)){
                        foreach ($citylist as $c_k => $city) {
                            $arealist=Db::name('system_city')->where('status',1)->order('sort,id')->field('name,id,pid')
                                ->where('pid',$city['id'])->cache(true,60*60*60*24*365*10)->select();
                            $citylist[$c_k]['sub_list']=$arealist;
                        }
                    }
                    $list[$p_k]['sub_list']=$citylist;
                }
            }

            $data['msg']='success';
            $data['data']=$list;
            return json($data);
        }catch(\Exception $e){
            return json(array('msg'=>$e->getMessage()),500);
        }
    }

    /**
     * 获取用户充值等级列表
     * @return \think\response\Json
     */
    public function user_grade_list()
    {
        try{
            $type=input('type',USER_TYPE_WORKER);
            //查询所有充值等级
            $list=Db::name('store_member_grade')->where('status',1)->where('type',$type)->hidden('type,status')->order('sort')->cache(60)->select();
            isset($list[0])?$list[0]['checked']=true:'';
            $data['msg']='success';
            $data['data']=$list;
            return json($data);
        }catch(\Exception $e){
            return json(array('msg'=>$e->getMessage()),500);
        }
    }

    /**
     * 上传文件
     * @return \think\response\Json
     */
    public function upload_pic()
    {
        try{
            $file = $this->request->file('file');
            if (!$file->checkImg()) {
                return json(['msg' => '只能上传图片类型文件'],403);
            }
            if (!$file->checkExt(strtolower(sysconf('storage_local_exts')))) {
                return json(['msg' => '文件上传类型受限'],403);
            }
            // 文件上传处理
            if (($info = $file->move("static/upload"))) {
                $filename=$info->getSaveName();
                if ($url = FileService::getFileUrl($filename, 'local')) {
                    $data['data']['url']=str_replace('\\','/',$url);
                    $data['msg']='文件上传成功';
                    return json($data);
                }
            }
            return json(['msg' => '文件上传失败'],500);
        }catch (\Exception $e){
            return json(['msg' => $e->getMessage()],500);
        }
    }

    /**
     * 返回系统文章详情
     * @return \think\response\Json
     */
    public function article()
    {
        try{
            $id=input('id',34);
            $article=app('systemCateService')::get_cate_by_id($id,'title,content');
            $data['msg']='success';
            $data['data']=$article;
            return json($data);
        }catch(\Exception $e){
            return json(['msg'=>$e->getMessage()],500);
        }

    }

    /**
     * 获取轮播图
     * @return \think\response\Json
     */
    public function banner()
    {
        try{
            $banner=Db::name('system_ad')->where('status',1)->where('type',17)->order('sort')
                ->cache(60)->field('id,image,url')->select();
            return json(['msg'=>'success','data'=>$banner]);
        }catch(\Exception $e){
            return json(['msg'=>$e->getMessage()],500);
        }
    }

    /**
     * 获取文字说明
     * @return \think\response\Json
     */
    public function get_note(){
        $page=input('page','point');//页面 point：我的积分 code：我的推荐码
        switch ($page){
            case 'point':
                $note[0]['content']='第一条说明';
                $note[1]['content']='第2条说明';
                break;
            case 'code':
                $note[0]['content']='第1条说明';
                $note[1]['content']='第2条说明';
                break;
        }
        return json(['msg'=>'success','data'=>$note]);
    }

    /*function test(){
        $mid=197;
        dump(MemberService::rebate($mid,100,'推荐用户['.$mid.']产生消费，获得佣金。'));
    }*/
}